import point from '@/assets/point.png';
import CommonModal from '@/components/CommonModal';
import AMapLoader from '@amap/amap-jsapi-loader';
import { Button, Modal, Space, message } from 'antd';
import { useEffect, useRef, useState } from 'react';
const ImportTest = () => {
  const [map, setMap] = useState<any>(null);
  const [mouseTool, setMouseTool] = useState<any>(null);
  const [activeIndex, setActiveIndex] = useState<string>('');
  const modalRef = useRef<any>(null);
  const [target, setTarget] = useState<any>(null);
  const [options, setOptions] = useState<any>({
    parameter: {
      zoom: 16, //级别
      //   center: [116.397428, 39.90923], //中心点坐标
      center: [116.398351, 39.912407],
      viewMode: '3D', //使用3D视图
    },
  });

  function drawCircle() {
    console.log(mouseTool, 'mouseTool');
    console.log(mouseTool?.circle, 'circle');

    mouseTool?.circle({
      strokeColor: '#FF33FF',
      strokeOpacity: 1,
      strokeWeight: 2,
      //   draggable: true,
      //   strokeOpacity: 0.2,
      fillColor: '#1791fc',
      fillOpacity: 0.4,
      strokeStyle: 'solid',
      // 线样式还支持 'dashed'
      // strokeDasharray: [30,10],
    });
  }

  function markPoint() {
    mouseTool?.marker();
  }
  useEffect(() => {
    mouseTool?.on('draw', (e: any) => {
      console.log(e, 'draw');
      const drawObj = e?.obj;
      if (drawObj?.type === 'AMap.Overlay') {
        const marks = map?.getAllOverlays()?.filter((item: any) => {
          return item?.type === 'AMap.Marker'; // 获取圆形区域的 所有标记点
        });
        console.log(marks, 'marks');
        const result = marks?.filter((item: any) => {
          const position = item?.getPosition();
          console.log(position, 'position');
          return drawObj?.contains(position);
        });
        if (result?.length > 0) {
          // console.log(result[0]?._position);

          Modal.confirm({
            title: '确定要向该区域发送信息吗?',
            content: (
              <div>
                {result?.map((item: any, index: number) => {
                  return (
                    <div key={index}>
                      <span>经度:{item?.getPosition()?.lng}</span>
                      <span>纬度:{item?.getPosition()?.lat}</span>
                    </div>
                  );
                })}
              </div>
            ),
            onOk: () => {
              message?.success('发送成功');
              // mark?.remove(); //清除最后一个mark
              mouseTool?.close(true);
              setActiveIndex('');
            },
            onCancel: () => {
              mouseTool?.close(true);
              setActiveIndex('');
            },
          });
        }
      } else if (drawObj?.type === 'AMap.Marker') {
        console.log(drawObj, 'Marker');
      }
    });
  }, [mouseTool]);

  useEffect(() => {
    AMapLoader.load({
      key: '33b4084992fd471752881796d36225fc',
      version: '2.0',
      plugins: ['AMap.MouseTool', 'AMap.ToolBar'],
    }).then((AMap) => {
      const toolBar = new AMap.ToolBar();
      const map = new AMap.Map('map-container', options?.parameter);
      // 初始化标记点
      const arr = [
        {
          position: [116.398351, 39.912407],
          content: `<div><img src=${point} class='w-[18px] h-[25px] transition-all duration-300 hover:scale-150'/></div>`,
        },
        {
          position: [116.398951, 39.912427],
          content: `<div><img src=${point} class='w-[18px] h-[25px]'/></div>`,
        },
      ];
      arr.forEach((item) => {
        const marker = new AMap.Marker({
          position: item?.position,
          content: item?.content,
        });
        marker.on('click', () => {
          console.log('click', item);
          setTarget(item);
          modalRef.current?.show();
        });
        map.add(marker);
      });

      //   aMap.clear(true); //清除所有mark
      ///marker.remove(); //清除某个mark
      map.addControl(toolBar);
      setMap(map);
      setMouseTool(new AMap.MouseTool(map));
    });
  }, []);
  return (
    <div className="w-full h-full">
      <div className="w-[1370px] h-[800px]" id="map-container"></div>
      <div className="fixed bottom-20 left-[280px]">
        <Space direction="vertical">
          {['绘制圆', '打点', '确定保存', '关闭工具', '清除圈选'].map(
            (item, index) => (
              <Button
                key={index}
                onClick={() => {
                  setActiveIndex(`${index}`);
                  if (`${index}` === '0') {
                    drawCircle();
                  } else if (`${index}` === '1') {
                    markPoint();
                  } else if (`${index}` === '2') {
                    console.log(map?.getAllOverlays(), 'map');
                    console.log('', '保存');
                  } else if (`${index}` === '3') {
                    // mouseTool?.destroy();
                    if (mouseTool) {
                      mouseTool?.close();
                    }
                    console.log(mouseTool, '销毁');
                  } else if (`${index}` === '4') {
                    mouseTool?.close(true);
                  }
                }}
                type={`${index}` === activeIndex ? 'primary' : 'default'}
              >
                {item}
              </Button>
            ),
          )}
        </Space>
      </div>
      <CommonModal title="确定要向该区域发送信息吗?" ref={modalRef}>
        <div>
          <span>经度:{target?.position[0]}</span>
          <span>纬度:{target?.position[1]}</span>
        </div>
      </CommonModal>
    </div>
  );
};

export default ImportTest;
